package com.zjy.business.common.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zjy.business.common.service.FileService;
import com.zjy.business.system.dao.SysConfigDao;
import com.zjy.business.system.domain.dto.FileConfigDto;
import com.zjy.common.constant.SysConfigEnum;
import com.zjy.common.utils.ImageUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * @author zhangjianyu
 * email: 578547270@qq.com
 * create_time: 2024-10-24 18:12
 * description:
 */
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
    private final SysConfigDao sysConfigDao;

    @Override
    public String getFilePrefix() {
        FileConfigDto fileConfigDto = sysConfigDao.queryConfigClass(SysConfigEnum.FILE_CONFIG, FileConfigDto.class);
        return fileConfigDto.getFilePrefix();
    }

    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        FileConfigDto fileConfigDto = sysConfigDao.queryConfigClass(SysConfigEnum.FILE_CONFIG, FileConfigDto.class);
        String fileName = file.getOriginalFilename();
        String suffix = getSuffix(fileName);
        StringBuilder builder = new StringBuilder()
                .append(DateUtil.format(new Date(), "yyyyMMdd"))
                .append("/")
                .append(System.currentTimeMillis())
                .append(suffix);
        String path = builder.toString();
        String saveFile = fileConfigDto.getFilePath() + path;
        File pathFile = new File(saveFile);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
            pathFile.delete();
        }
        file.transferTo(pathFile);
        ImageUtils.zipImage(pathFile);
        return path;
    }

    /**
     * 获取文件的后缀名
     *
     * @param fileName 文件的名称，包括可能的路径和后缀名
     * @return 文件的后缀名，如果文件没有后缀名则返回空字符串
     */
    public String getSuffix(String fileName) {
        int i = fileName.lastIndexOf(".");
        if (i > 0) {
            return fileName.substring(i);
        } else {
            return "";
        }
    }
}
